package com.tangtang.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.tangtang.security.model.SysUser;
import com.tangtang.security.model.SysUserRoleKey;
import com.tangtang.security.service.UserService;

public class MyUserDetailsService implements UserDetailsService
{
	
	UserService	userService;
	
	public UserService getUserService()
	{
		return userService;
	}
	
	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{
		SysUser sysUser = userService.getUser(username);
		if (sysUser == null)
		{
			throw new UsernameNotFoundException("用户名不存在");
		}
		
		List<SysUserRoleKey> rolesList = userService.getRolesByUserId(sysUser.getUserId());
		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		if (rolesList != null && rolesList.size() > 0)
		{
			for (SysUserRoleKey role : rolesList)
			{
				SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleId().toString());
				auths.add(authority);
			}
		}
		MyUserDetails userDetails = new MyUserDetails(sysUser.getUserId(), username, sysUser.getUserPassword(), true, true, true, true, auths);
		return userDetails;
	}
	
}
